#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from PIL import Image, ImageDraw
from cv2 import Stitcher
from os import listdir
import sys
import json
from collections import OrderedDict
import cv2
import cv2 as cv
import numpy as np
import math

PIC_NAME="images_"

def eachFile(filepath):
    pic_name=[]
    pathDir=os.listdir(filepath)
    for allDir in pathDir:
        child=os.path.join('%s%s'%(filepath,allDir))
        pic_name.append(child)
    return pic_name

def out_nums(img2):
    b, g, r = cv2.split(img2)  # 三通道分离
    ret1, out = cv2.threshold(b, 0, 100, cv2.THRESH_BINARY)  # 二值化
    # # edges = cv.Canny(out, 100, 200)
    # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
    contours, hierarchy = cv2.findContours(
        out, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等
    cv2.drawContours(out, contours, -1, (255, 255, 255), thickness=None,
                     lineType=None, hierarchy=None, maxLevel=None, offset=None)
    n = len(contours)  # 轮廓个数
    print(contours[0].shape,contours[0][1],contours[0][2],contours[0][2])
    ccnt = 0
    for i in range(n):
        length = cv2.arcLength(contours[i], True)  # 获取轮廓长度
        area = cv2.contourArea(contours[i])  # 获取轮廓面积
        if length > 10 and area > 10 and length < 100 and area < 100:
            # print('length['+str(i)+']长度=', length)
            # print("contours["+str(i)+"]面积=", area)
            ccnt += 1
    print("个数：", ccnt)
    # cv2.imshow('out', out)  # 显示原始图像


def Get_Average(list):
    msum = 0
    for item in list:
        msum += item
    a = msum/len(list)
    return [int(a[0][0]), int(a[0][1])]


def eucliDist(A, B):
    return math.sqrt(sum([(a - b) ** 2 for (a, b) in zip(A, B)]))


def find_xys(img2):
    pose = []

    lengths=0
    areas=0
    b, g, r = cv2.split(img2)  # 三通道分离
    # cv2.imshow("b",b)

    ret1, out = cv2.threshold(b, 17, 100, cv2.THRESH_BINARY)  # 二值化
    # # edges = cv.Canny(out, 100, 200)
    # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
    binary, contours, hierarchy = cv2.findContours(
        out, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)  # 检索模式为树形cv2.RETR_TREE，
    # 轮廓存储模式为简单模式cv2.CHAIN_APPROX_SIMPLE，如果设置为 cv2.CHAIN_APPROX_NONE，所有的边界点都会被存储。
    # 第三个参数是轮廓的索引（在绘制独立轮廓是很有用，当设置为 -1 时绘制所有轮廓）。接下来的参数是轮廓的颜色和厚度等
    # cv2.drawContours(out, contours, -1, (255, 255, 255), thickness=None,
    #                  lineType=None, hierarchy=None, maxLevel=None, offset=None)
    cv2.drawContours(out, contours, -1, (255, 255, 255))
    n = len(contours)  # 轮廓个数
    print(n)
    for i in range(n):
        length = cv2.arcLength(contours[i], True)  # 获取轮廓长度
        area = cv2.contourArea(contours[i])  # 获取轮廓面积
        # if length > 10 and area > 10 and length < 100 and area < 100:
        if length > 0 and area > 0 and length < 90 and area < 90:
            pose.append(Get_Average(contours[i]))
    print("个数：", len(pose))
    return pose,out,




def cutpic(imgrgb):
    srcheight = int(imgrgb.shape[0])
    srcwidth = int(imgrgb.shape[1])
    print(srcheight,srcwidth)
    sx = 0
    ex = 0
    ey = 0
    sy = 0

    for i in range(srcheight):
        if(sum(sum(imgrgb[i, ])) !=0):
            if i==0:
                print(sx)
                print(sum(sum(imgrgb[i,])))
            else:
                sx = i-1
                print(sx)
                print(sum(sum(imgrgb[i,])))
            break
    for i in range(srcwidth):
        if(sum(sum(imgrgb[:, i])) !=0):
            if i==0:
                print(sx)
                print(sum(sum(imgrgb[:,i])))
            else:
                sy = i-1
                print(sy)
                print(sum(sum(imgrgb[:, i])))
            break
    for i in range(srcheight):
        if(sum(sum(imgrgb[srcheight-1-i, ])) !=0):
            ex = srcheight-i+1
            print(ex)
            print(sum(sum(imgrgb[srcheight-1-i, ])))
            break
    for i in range(srcwidth):
        if(sum(sum(imgrgb[:, srcwidth-1-i])) !=0):
            ey = srcwidth-i+1
            print(ey)
            print(sum(sum(imgrgb[:, srcwidth-1-i])))
            break
    imgbk = imgrgb[sx:ex, sy:ey]
    cv2.imwrite('result.png', imgbk)
    return imgbk

def calMatchPose(srcimg, dstimg):
    b1, g1, r1 = cv2.split(srcimg)  # 三通道分离
    b2, g2, r2 = cv2.split(dstimg)  # 三通道分离
    out1 = r1-b1
    out2 = r2-b2
    orb = cv.ORB_create()
    kpSRC, desCat = orb.detectAndCompute(out1, None)
    kpDST, desSmallCat = orb.detectAndCompute(out2, None)
    bf = cv.BFMatcher_create(cv.NORM_HAMMING, crossCheck=True)
    matches = bf.match(desCat, desSmallCat)
    good_match = sorted(matches, key=lambda x: x.distance)
    matchImg = cv.drawMatches(
        out1, kpSRC, out2, kpDST, good_match[: 9], None)
    ma = good_match[0]
    return ((kpSRC[ma.queryIdx].pt[0]-kpDST[ma.trainIdx].pt[0]), (kpSRC[ma.queryIdx].pt[1]-kpDST[ma.trainIdx].pt[1])), matchImg, out1, out2




def show_mached2(pose, bkgdimg, srcimg, dstimg):
    # image = cv2. imread(PATH+"image_"+str(3)+".png")

    dstheight = int(dstimg.shape[0])
    dstwidth = int(dstimg.shape[1])
    srcheight = int(srcimg.shape[0])
    srcwidth = int(srcimg.shape[1])
    for i in range(dstheight):
        for j in range(dstwidth):
            bkgdimg[i+200, j+400] = dstimg[i, j]
    for i in range(srcheight):
        for j in range(srcwidth):
            bkgdimg[i-int(pose[1])+200, j-int(pose[0])+400] = srcimg[i, j]
    return bkgdimg


def read_client_path():

    with open("./sesson2/subject1/subject_1/client_path_6.json", 'r') as load_f:
        load_dict = json.load(load_f)
        print(load_dict['race_time'])
        print(load_dict['send_id'])
        # print(load_dict['image_path'])
    return load_dict['send_id'],load_dict['image_path']


def toJons(sum,id,path):
    x=OrderedDict()
    x["rescue_people_total:"]=sum
    x["operate_id"]=id
    x["pic_path"]=path
    with open('./sesson2/subject1/subject_1/team_path_6.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(x, ensure_ascii=False, indent=4))





